<template>
  <div class="chat-history-manage-container">
    <a-card class="chat-history-manage-card">


      <!-- 搜索表单 -->
      <a-form class="search-form" layout="inline">
        <a-form-item label="消息内容">
          <a-input
            v-model:value="searchParams.message"
            placeholder="搜索消息内容"
            allow-clear
            style="width: 200px"
          />
        </a-form-item>

        <a-form-item label="消息类型">
          <a-select
            v-model:value="searchParams.messageType"
            placeholder="选择消息类型"
            allow-clear
            style="width: 120px"
          >
            <a-select-option value="user">用户消息</a-select-option>
            <a-select-option value="ai">AI回复</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="应用ID">
          <a-input-number
            v-model:value="searchParams.appId"
            placeholder="应用ID"
            allow-clear
            style="width: 120px"
          />
        </a-form-item>

        <a-form-item label="用户ID">
          <a-input-number
            v-model:value="searchParams.userId"
            placeholder="用户ID"
            allow-clear
            style="width: 120px"
          />
        </a-form-item>

        <a-form-item>
          <a-space>
            <a-button type="primary" @click="doSearch">
              <template #icon><SearchOutlined /></template>
              搜索
            </a-button>
            <a-button @click="resetSearch">
              <template #icon><ReloadOutlined /></template>
              重置
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>

      <a-divider style="margin: 16px 0" />

      <!-- 数据表格 -->
      <a-table
        :columns="columns"
        :data-source="data"
        :pagination="pagination"
        @change="doTableChange"
        :loading="loading"
        :rowKey="record => record.id"
        :scroll="{ x: 1200 }"
        bordered
      >
        <template #bodyCell="{ column, record }">
          <!-- 消息内容 -->
          <template v-if="column.dataIndex === 'message'">
            <div class="message-cell">
              <a-tooltip :title="record.message">
                <div class="message-preview">
                  {{ record.message || '无内容' }}
                </div>
              </a-tooltip>
            </div>
          </template>

          <!-- 消息类型 -->
          <template v-else-if="column.dataIndex === 'messageType'">
            <a-tag :color="getMessageTypeColor(record.messageType)">
              {{ getMessageTypeName(record.messageType) }}
            </a-tag>
          </template>

          <!-- 应用信息 -->
          <template v-else-if="column.dataIndex === 'appId'">
            <div class="app-cell">
              <span class="app-id">#{{ record.appId }}</span>
            </div>
          </template>

          <!-- 用户信息 -->
          <template v-else-if="column.dataIndex === 'userId'">
            <div class="user-cell">
              <span class="user-id">#{{ record.userId }}</span>
            </div>
          </template>

          <!-- 创建时间 -->
          <template v-else-if="column.dataIndex === 'createTime'">
            {{ formatDate(record.createTime) }}
          </template>

          <!-- 操作 -->
          <template v-else-if="column.dataIndex === 'action'">
            <a-space>
              <a-tooltip title="查看详情">
                <a-button type="primary" size="small" @click="viewDetail(record)">
                  <template #icon><EyeOutlined /></template>
                </a-button>
              </a-tooltip>

              <DeleteConfirm
                :title="`确定要删除这条对话记录吗？`"
                @confirm="doDelete(record.id)"
              >
                <a-tooltip title="删除记录">
                  <a-button type="primary" danger size="small">
                    <template #icon><DeleteOutlined /></template>
                  </a-button>
                </a-tooltip>
              </DeleteConfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 详情模态框 -->
    <a-modal
      v-model:open="detailModalVisible"
      title="对话详情"
      :footer="null"
      width="800px"
    >
      <div v-if="selectedRecord" class="detail-content">
        <a-descriptions :column="2" bordered>
          <a-descriptions-item label="记录ID">
            {{ selectedRecord.id }}
          </a-descriptions-item>

          <a-descriptions-item label="消息类型">
            <a-tag :color="getMessageTypeColor(selectedRecord.messageType)">
              {{ getMessageTypeName(selectedRecord.messageType) }}
            </a-tag>
          </a-descriptions-item>

          <a-descriptions-item label="应用ID">
            {{ selectedRecord.appId }}
          </a-descriptions-item>

          <a-descriptions-item label="用户ID">
            {{ selectedRecord.userId }}
          </a-descriptions-item>

          <a-descriptions-item label="创建时间">
            {{ formatDate(selectedRecord.createTime) }}
          </a-descriptions-item>

          <a-descriptions-item label="更新时间">
            {{ formatDate(selectedRecord.updateTime) }}
          </a-descriptions-item>

          <a-descriptions-item label="消息内容" :span="2">
            <div class="message-detail">
              <pre>{{ selectedRecord.message }}</pre>
            </div>
          </a-descriptions-item>
        </a-descriptions>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { listAllChatHistoryByPageForAdmin } from '@/api/chatHistoryController'
import { useLoginUserStore } from '@/stores/useLoginUserStore'
import {
  SearchOutlined,
  ReloadOutlined,
  DeleteOutlined,
  EyeOutlined
} from '@ant-design/icons-vue'
import dayjs from 'dayjs'
import DeleteConfirm from '@/components/DeleteConfirm.vue'

const router = useRouter()
const loginUserStore = useLoginUserStore()

// 表格列配置
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 80,
  },
  {
    title: '消息内容',
    dataIndex: 'message',
    key: 'message',
    width: 300,
    ellipsis: true,
  },
  {
    title: '消息类型',
    dataIndex: 'messageType',
    key: 'messageType',
    width: 100,
  },
  {
    title: '应用ID',
    dataIndex: 'appId',
    key: 'appId',
    width: 100,
  },
  {
    title: '用户ID',
    dataIndex: 'userId',
    key: 'userId',
    width: 100,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: 180,
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    width: 120,
    fixed: 'right',
  },
]

// 搜索参数
const searchParams = reactive<API.ChatHistoryQueryRequest>({
  pageNum: 1,
  pageSize: 10,
  sortField: 'createTime',
  sortOrder: 'desc'
})

// 数据状态
const data = ref<API.ChatHistory[]>([])
const total = ref(0)
const loading = ref(false)

// 详情模态框
const detailModalVisible = ref(false)
const selectedRecord = ref<API.ChatHistory>()

/**
 * 获取数据
 */
const fetchData = async () => {
  loading.value = true
  try {
    const res = await listAllChatHistoryByPageForAdmin(searchParams)

    if (res.data.code === 0 && res.data.data) {
      data.value = res.data.data.records || []
      total.value = res.data.data.totalRow || 0
      console.log('对话数据加载成功:', res.data.data)
    } else {
      message.error('获取数据失败：' + res.data.message)
    }
  } catch (error) {
    message.error('获取数据失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}

/**
 * 分页配置
 */
const pagination = computed(() => {
  return {
    current: searchParams.pageNum ?? 1,
    pageSize: searchParams.pageSize ?? 10,
    total: total.value,
    showSizeChanger: true,
    showTotal: (total: number) => `共 ${total} 条`,
  }
})

/**
 * 表格变化处理
 */
const doTableChange = (page: any) => {
  searchParams.pageNum = page.current
  searchParams.pageSize = page.pageSize
  fetchData()
}

/**
 * 搜索处理
 */
const doSearch = () => {
  searchParams.pageNum = 1
  fetchData()
}

/**
 * 重置搜索
 */
const resetSearch = () => {
  searchParams.message = undefined
  searchParams.messageType = undefined
  searchParams.appId = undefined
  searchParams.userId = undefined
  searchParams.pageNum = 1
  fetchData()
}

/**
 * 删除记录
 */
const doDelete = async (id: number) => {
  try {
    // 注意：这里需要后端提供删除接口，暂时用message提示
    message.warning('删除功能需要后端接口支持')
    // const res = await deleteChatHistory({ id })
    // if (res.data.code === 0) {
    //   message.success('删除成功')
    //   fetchData()
    // } else {
    //   message.error('删除失败：' + res.data.message)
    // }
  } catch (error) {
    message.error('删除失败，请稍后重试')
  }
}

/**
 * 查看详情
 */
const viewDetail = (record: API.ChatHistory) => {
  selectedRecord.value = record
  detailModalVisible.value = true
}

/**
 * 根据消息类型获取颜色
 */
const getMessageTypeColor = (type?: string) => {
  const colorMap: Record<string, string> = {
    user: 'blue',
    ai: 'green'
  }
  return colorMap[type || ''] || 'default'
}

/**
 * 根据消息类型获取名称
 */
const getMessageTypeName = (type?: string) => {
  const nameMap: Record<string, string> = {
    user: '用户消息',
    ai: 'AI回复'
  }
  return nameMap[type || ''] || '未知类型'
}

/**
 * 格式化时间
 */
const formatDate = (dateString?: string) => {
  if (!dateString) return '-'
  return dayjs(dateString).format('YYYY-MM-DD HH:mm:ss')
}

// 页面加载时获取数据
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.chat-history-manage-container {
  padding: 24px;
  min-height: 100vh;
  background: #f5f5f5;
}

.chat-history-manage-card {
  margin-bottom: 24px;
  box-shadow: 0 1px 2px -2px rgba(0, 0, 0, 0.16),
    0 3px 6px 0 rgba(0, 0, 0, 0.12),
    0 5px 12px 4px rgba(0, 0, 0, 0.09);
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #262626;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #8c8c8c;
  font-size: 14px;
}

.search-form {
  margin-bottom: 16px;
}

.search-form .ant-form-item {
  margin-bottom: 8px;
}

/* 消息内容单元格 */
.message-cell {
  max-width: 300px;
}

.message-preview {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 280px;
}

/* 应用单元格 */
.app-cell {
  display: flex;
  align-items: center;
}

.app-id {
  font-family: 'Monaco', 'Consolas', monospace;
  font-size: 13px;
  color: #1890ff;
  font-weight: 500;
}

/* 用户单元格 */
.user-cell {
  display: flex;
  align-items: center;
}

.user-id {
  font-family: 'Monaco', 'Consolas', monospace;
  font-size: 13px;
  color: #52c41a;
  font-weight: 500;
}

/* 详情内容 */
.detail-content {
  padding: 16px 0;
}

.message-detail {
  max-height: 300px;
  overflow-y: auto;
  background: #fafafa;
  padding: 12px;
  border-radius: 4px;
  border: 1px solid #e8e8e8;
}

.message-detail pre {
  white-space: pre-wrap;
  word-break: break-all;
  margin: 0;
  font-family: inherit;
  font-size: 14px;
  line-height: 1.5;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
  }

  .search-form .ant-form-item {
    width: 100%;
  }

  .search-form .ant-input,
  .search-form .ant-select,
  .search-form .ant-input-number {
    width: 100% !important;
  }
}
</style>
